﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SDF.Plugin.Misc.SAPAdapter.Domain;
using SDF.Core.Data;
using SDF.Services.Events;
using SDF.Core;

namespace SDF.Plugin.Misc.SAPAdapter.Services
{
    public class SAPInstanceService : ISAPInstanceService
    {
        private readonly IRepository<SAPInstance> _sapClientRep;
        private readonly IEventPublisher _eventPublisher;

        public SAPInstanceService(
            IRepository<SAPInstance> sapClientRep,
            IEventPublisher eventPublisher)
        {
            this._sapClientRep = sapClientRep;
            this._eventPublisher = eventPublisher;
        }

        public void InsertSAPInstance(SAPInstance entity)
        {
            _sapClientRep.Insert(entity);

            _eventPublisher.EntityInserted(entity);
        }

        public IEnumerable<SAPInstance> GetAllInstance(bool showDel = false)
        {
            var query = _sapClientRep.TableNoTracking.OrderBy(p => p.SortNo);
            if (showDel == false)
                query.Where(p => p.Delete.Equals(false));

            return query;
        }

        public IPagedList<SAPInstance> QuerySAPInstance(string sapInstance, int pageIndex = 0, int pageSize = int.MaxValue,
            bool showDel = false)
        {
            var query = _sapClientRep.TableNoTracking;

            if (sapInstance.IsNullOrEmpty() == false)
                query = query.Where(p => p.CodeName.Contains(sapInstance));

            if (showDel == false)
                query = query.Where(p => p.Delete == false);

            query = query.OrderByDescending(p => p.CreateTimeOnUtc);

            var result = new PagedList<SAPInstance>(query, pageIndex, pageSize);

            return result;
        }

        public SAPInstance GetSAPInstanceById(int id)
        {
            return _sapClientRep.Table.FirstOrDefault(p => p.Id.Equals(id));
        }

        public SAPInstance GetSAPInstanceByCodeName(string codeName)
        {
            codeName.NullOrEmptyCheck("codeName");

            return _sapClientRep.Table.FirstOrDefault(p => p.CodeName.Equals(codeName));
        }

        public void UpdateSAPInstance(SAPInstance entity)
        {
            _sapClientRep.Update(entity);

            _eventPublisher.EntityUpdated(entity);
        }

        public void DeleteSAPInstance(SAPInstance entity)
        {
            _sapClientRep.Delete(entity);

            _eventPublisher.EntityDeleted(entity);
        }
    }
}